// 同步action
export const add_brand=function(data){
    return {type:'add_brand',data}
}
export const del_brand=function(data){
    return {type:'del_brand',data}
}
export const update_brand=function(data){
    return {type:'update_brand',data}
}
export const get_brands=function(data){
    return {type:'get_brands',data}
}

// 重置品牌名称
export const reset_brand_name=function(data){
    return {type:'reset_brand_name',data}
}
// 重置即将被更新的品牌对象
export const reset_current_brand=function(data){
    return {type:'reset_current_brand',data}
}


// 异步action
export const get_brands_async=function(){
    return function(dispatch){
          // 请求数据
        fetch(`http://106.13.182.88:3001/brand`).then(response=>response.json()).then(res=>{
            // 触发同步action
            dispatch(get_brands(res.message));
        });
    }
}

export const del_brand_async=function(id){
    return (dispatch)=>{
        // 请求数据接口, 实现删除操作
        fetch(`http://106.13.182.88:3001/brand/${id}`,{method:'DELETE'}).then((response)=>response.json()).then(res=>{
            // 触发同步删除action
            dispatch(del_brand(id));
        })
    }
}

export const add_brand_async=function(data){
    return (dispatch)=>{
        // 发送请求, 将品牌数据提交给数据接口
        fetch(`http://106.13.182.88:3001/brand`,{
            method:'POST',
            body:`name=${data.name}`,
            headers:{
                'Content-Type':'application/x-www-form-urlencoded'
            }
        }).then(response=>response.json()).then(res=>{
            // 触发同步action, 实现新增品牌
            // data={id,name,ctime}
            // 服务端返回的品牌id
            data.id=res.id;
            dispatch(add_brand(data));
        })
    }
}

export function reset_current_brand_async(data){
    return (dispatch)=>{
        // 发送请求, 将品牌数据提交给数据接口
        fetch(`http://106.13.182.88:3001/brand/${data.id}`,{
            method:'PUT',
            body:`name=${data.name}`,
            headers:{
                'Content-Type':'application/x-www-form-urlencoded'
            }
        }).then(response=>response.json()).then(res=>{
            // 触发同步action, 实现更新品牌列表
            dispatch(update_brand(data));
        })
    }
}